package com.chungkui.check.core;

import com.chungkui.check.annotation.Check;
import com.chungkui.check.core.bean.CheckResult;
import com.chungkui.check.util.JsonUtil;
import com.google.common.collect.Maps;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * @Author: jason
 * @Date: 2020/1/2 17:46
 * @Version 1.0
 */
public class DefaultMsgBuilder implements MsgBuilder {


    private String globalMsgTemplate = "{param:'#param',val:'#val',code:'#code',msg:'#msg'}";

    @Override
    public void setGlobalMsgTemplate(String globalMsgTemplate) {
        this.globalMsgTemplate = globalMsgTemplate;
    }

    public DefaultMsgBuilder() {
    }


    public DefaultMsgBuilder(String globalMsgTemplate) {
        this.globalMsgTemplate = globalMsgTemplate;
    }


    public Map<String, Object> buildFailMapMsg(CheckResult result, Check check) {
          return JsonUtil.json2map(buildFailJson(result,check));
    }

    private String buildFailJson(CheckResult result, Check check) {
        String msgtmp = check.msgTemp();
        String[] searchList = {Constants.CODE_REPLACE, Constants.MSG_REPLACE, Constants.PARAM_REPLACE, Constants.VAL_REPLACE};
        String[] paramList = {
                StringUtils.isEmpty(result.getCode()) ? "" : result.getCode(),
                result.getMsg(),
                StringUtils.isEmpty(result.getParam()) ? "" : result.getParam(),
                StringUtils.isEmpty(result.getVal()) ? "" : result.getVal()};
        return StringUtils.replaceEach(StringUtils.isNotEmpty(msgtmp) ? msgtmp : this.globalMsgTemplate, searchList, paramList);

    }

    @Override
    public Object buildFailMsg(CheckResult result, Check check, Class returnType) {
        if (returnType == Object.class||returnType == Map.class) {
            return buildFailMapMsg(result, check);
        }
        if (returnType == String.class) {
            return buildFailJson(result,check);
        }
        return JsonUtil.jsonToObject(buildFailJson(result,check), returnType);
    }

    /**
     * 消息格式配置{success:'200',codeKey:'code',dataKey:'data',msgKey:'msg',paramKey:'param'}
     *
     * @param check
     * @param data
     * @return
     */
    @Override
    public Object buildSuccessMsg(Check check, Object data) {
        return data;
    }
}
